//
//  inMoneyViewController.m
//  WZEfengAndEtong
//
//  Created by 李旭 on 16/9/26.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "inMoneyViewController.h"
#import "MBProgressHUD.h"
#import "Masonry.h"
#import "CXmppRequestMgr.h"
#import "moneyInfoViewController.h"
#import "CContactModel.h"
#import "JKAlertDialog.h"
//#import <AlipaySDK/AlipaySDK.h>
@interface inMoneyViewController ()
@property(nonatomic,weak)UITextField *moneyTextField;
@property(nonatomic,weak)UILabel *resultLabel;
@property(nonatomic,weak)UILabel *anotherMoney;
@property(nonatomic,weak)UIImageView *weixin;
@property(nonatomic,weak)UIImageView *zhifubao;

@end

@implementation inMoneyViewController
+(instancetype)sharedInstacet {
    static dispatch_once_t onceToken;
    static inMoneyViewController *instance;
    dispatch_once(&onceToken, ^{
        instance = [[inMoneyViewController alloc] init];
    });
    return instance;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setNewTitleCenter:@"充值"];
    self.view.backgroundColor = RGBCOLOR(243, 243, 243);
    [self configInterFace];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.moneyTextField.text = nil;
    self.resultLabel.text = nil;
    self.anotherMoney.text = @"0.00";
    self.weixin.hidden = NO;
    self.zhifubao.hidden = YES;
}
-(void)configInterFace
{
    UIView *moneyView = [[UIView alloc]init];
    moneyView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:moneyView];
    [moneyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(60);
    }];
    UILabel *jinElabel = [[UILabel alloc]init];
    jinElabel.text = @"金额";
    jinElabel.textAlignment = NSTextAlignmentCenter;
    [moneyView addSubview:jinElabel];
    [jinElabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.width.mas_equalTo(40);
        make.top.bottom.mas_equalTo(0);
    }];
    UILabel *yuanLabel = [[UILabel alloc]init];
    yuanLabel.textAlignment = NSTextAlignmentCenter;
    yuanLabel.text = @"元";
    [moneyView addSubview:yuanLabel];
    [yuanLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.mas_equalTo(0);
        make.width.mas_equalTo(40);
    }];
    UITextField *money = [[UITextField alloc]init];
    money.keyboardType = UIKeyboardTypeDecimalPad;
    money.borderStyle = UITextBorderStyleNone;
    money.textAlignment = NSTextAlignmentRight;
    money.placeholder = @"请输入金额";
    self.moneyTextField = money;
    [money addTarget:self action:@selector(changeValue) forControlEvents:UIControlEventEditingChanged];
    [moneyView addSubview:money];
    [money mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(jinElabel.mas_right).offset(0);
        make.right.equalTo(yuanLabel.mas_left).offset(0);
        make.bottom.top.mas_equalTo(0);
    }];
    UILabel *fangshiLabel = [[UILabel alloc]init];
    fangshiLabel.textAlignment = NSTextAlignmentLeft;
    fangshiLabel.text = @"请选择支付方式";
    fangshiLabel.textColor = RGBCOLORWITH16COLOR(0x999999);
    [self.view addSubview:fangshiLabel];
    [fangshiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(10);
        make.top.equalTo(moneyView.mas_bottom).offset(5);
        make.height.mas_equalTo(30);
    }];
    UIView *weixinView = [[UIView alloc]init];
    UITapGestureRecognizer *tapwei=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(choseWeixin)];
    [weixinView addGestureRecognizer:tapwei];
    weixinView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:weixinView];
    [weixinView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(fangshiLabel.mas_bottom).offset(5);
        make.height.mas_equalTo(60);
    }];
    UIImageView *weixinhead = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"weixin"]];
    weixinhead.layer.cornerRadius = 20;
    weixinhead.layer.masksToBounds = YES;
    [weixinView addSubview:weixinhead];
    [weixinhead mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.width.height.mas_equalTo(40);
        make.centerY.mas_equalTo(weixinView);
    }];
    
    UILabel *weixinLabel = [[UILabel alloc]init];
    weixinLabel.text = @"微信支付";
    weixinLabel.textAlignment = NSTextAlignmentLeft;
    [weixinView addSubview:weixinLabel];
    [weixinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weixinhead.mas_right).offset(10);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(100);
    }];
    UIImageView *weixinSelect = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"choseicon"]];
    [weixinView addSubview:weixinSelect];
    weixinSelect.hidden = YES;
    self.weixin = weixinSelect;
    [weixinSelect mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-30);
        make.width.height.mas_equalTo(20);
        make.centerY.mas_equalTo(weixinView);
    }];
    
    
    
    
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
        make.top.equalTo(weixinView.mas_bottom).offset(0);
    }];
    UIView *zhifubaoView = [[UIView alloc]init];
    zhifubaoView.backgroundColor = [UIColor whiteColor];
    UITapGestureRecognizer *tapZhi=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(choseZhifubao)];
    [zhifubaoView addGestureRecognizer:tapZhi];
    [self.view addSubview:zhifubaoView];
    [zhifubaoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(line.mas_bottom).offset(0);
        make.height.mas_equalTo(60);
    }];
    UIImageView *zhifubaohead = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"zhifubao"]];
    zhifubaohead.layer.cornerRadius = 20;
    zhifubaohead.layer.masksToBounds = YES;
    [zhifubaoView addSubview:zhifubaohead];
    [zhifubaohead mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.width.height.mas_equalTo(40);
        make.centerY.mas_equalTo(zhifubaoView);
    }];
    
    UILabel *zhifubaoLabel = [[UILabel alloc]init];
    zhifubaoLabel.text = @"支付宝支付";
    zhifubaoLabel.textAlignment = NSTextAlignmentLeft;
    [zhifubaoView addSubview:zhifubaoLabel];
    [zhifubaoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zhifubaohead.mas_right).offset(10);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(100);
    }];
    UIImageView *zhifubaoSelect = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"choseicon"]];
    [zhifubaoView addSubview:zhifubaoSelect];
    zhifubaoSelect.hidden = YES;
    self.zhifubao = zhifubaoSelect;
    [zhifubaoSelect mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-30);
        make.width.height.mas_equalTo(20);
        make.centerY.mas_equalTo(zhifubaoView);
    }];

    UILabel *labelA = [[UILabel alloc]init];
    labelA.text = @"手续费";
    labelA.textColor = RGBCOLORWITH16COLOR(0x999999);
    labelA.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:labelA];
    [labelA mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.equalTo(zhifubaoView.mas_bottom).offset(10);
        make.height.mas_equalTo(20);
        make.width.mas_equalTo(40);
    }];
    UILabel *labelAnother =[[UILabel alloc]init];
    labelAnother.text = @"0.00";
    labelAnother.textAlignment = NSTextAlignmentCenter;
    labelAnother.font = [UIFont systemFontOfSize:13];
    labelAnother.textColor = [UIColor redColor];
    [self.view addSubview:labelAnother];
    self.anotherMoney = labelAnother;
    [labelAnother mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(labelA.mas_right).offset(0);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(20);
        make.top.equalTo(zhifubaoView.mas_bottom).offset(10);
    }];
    UILabel *yuanAnother =[[UILabel alloc]init];
    yuanAnother.text = @"元";
    yuanAnother.textAlignment = NSTextAlignmentLeft;
    yuanAnother.font = [UIFont systemFontOfSize:13];
    yuanAnother.textColor = RGBCOLORWITH16COLOR(0x999999);
    [self.view addSubview:yuanAnother];
    [yuanAnother mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(labelAnother.mas_right).offset(0);
        make.width.height.mas_equalTo(20);
        make.top.equalTo(zhifubaoView.mas_bottom).offset(10);
    }];
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [infoButton setTitle:@"手续费说明" forState:UIControlStateNormal];
    infoButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [infoButton setBackgroundColor:[UIColor clearColor]];
    [infoButton addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
    [infoButton setTitleColor:RGBCOLORWITH16COLOR(0x2caafe) forState:UIControlStateNormal];
    [self.view addSubview:infoButton];
    [infoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.top.equalTo(zhifubaoView.mas_bottom).offset(10);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(20);
    }];

    UIView *resultView = [[UIView alloc]init];
    resultView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:resultView];
    [resultView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(infoButton.mas_bottom).offset(20);
        make.height.mas_equalTo(60);
    }];
    UILabel *noticeLabel = [[UILabel alloc]init];
    noticeLabel.text = @"您需要支付";
    noticeLabel.font = [UIFont systemFontOfSize:15];
    noticeLabel.textAlignment = NSTextAlignmentLeft;
    [resultView addSubview:noticeLabel];
    [noticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(100);
    }];
    UILabel *resultLabel = [[UILabel alloc]init];
    resultLabel.textAlignment = NSTextAlignmentRight;
    resultLabel.textColor = [UIColor redColor];
    resultLabel.font = [UIFont systemFontOfSize:25];
    self.resultLabel = resultLabel;
    [resultView addSubview:resultLabel];
    [resultLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(150);
    }];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = RGBCOLOR(44, 170, 253);
    [button setTitle:@"提交" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:25];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(chongzhi) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 5;
    button.layer.masksToBounds = YES;
    [self.view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(-20);
        make.left.mas_equalTo(20);
        make.bottom.mas_equalTo(-20);
    }];
}
-(void)choseWeixin
{
    self.weixin.hidden = NO;
    self.zhifubao.hidden = YES;
}
-(void)choseZhifubao
{
//    [MBProgressHUD showError:@"暂时不支持支付宝支付"];
//    return;
//    self.weixin.hidden = YES;
//    self.zhifubao.hidden = NO;
    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"提示" message:@"当前暂不支持支付宝支付"];
    [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
    }];
    [alert show];
    


}
-(void)changeValue
{
    self.anotherMoney.text = [NSString stringWithFormat:@"%.2f",[self.moneyTextField.text floatValue]*0.001];
    self.resultLabel.text = [NSString stringWithFormat:@"%@%.2f",@"¥",([self.moneyTextField.text floatValue]+[self.anotherMoney.text floatValue])];
}
-(void)showInfo
{
    moneyInfoViewController *info = [[moneyInfoViewController alloc]init];
    [self.navigationController pushViewController:info animated:YES];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
-(void)chongzhi
{
    NSString *money = [self.resultLabel.text substringFromIndex:1];
    if (!self.weixin.hidden) {
        if (self.moneyTextField.text.doubleValue < 0.01) {
            [MBProgressHUD showError:@"最少充值1分"];
            return;
        }
        if (![WXApi isWXAppInstalled]) {
            [MBProgressHUD showError:@"未检测到微信客户端"];
            return;
        }
        if (![WXApi isWXAppSupportApi]) {
            [MBProgressHUD showError:@"微信版本过低请升级"];
            return;
        }
        [[CXmppRequestMgr shareInstance] getSignWithUserId:self.currentUser.UserID AndMoney:[money doubleValue] AndType:1 successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSMutableDictionary *dict = responseObject[0];
            if([[dict objectForKey:@"result"] isEqualToString:@"success"]){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                [WXApi sendReq:req];
            }
            else
            {
                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"提示" message:@"支付订单生成失败，请重试"];
                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                }];
                [alert show];
            }
        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD showError:@"充值服务器异常"];
        }];

    }
   else if (!self.zhifubao.hidden) {
       [[CXmppRequestMgr shareInstance] getSignWithUserId:self.currentUser.UserID AndMoney:[money doubleValue] AndType:2 successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
           NSMutableDictionary *dict = responseObject[0];
           if([[dict objectForKey:@"result"] isEqualToString:@"success"]){
               NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
               PayReq* req             = [[PayReq alloc] init];
               req.partnerId           = [dict objectForKey:@"partnerid"];
               req.prepayId            = [dict objectForKey:@"prepayid"];
               req.nonceStr            = [dict objectForKey:@"noncestr"];
               req.timeStamp           = stamp.intValue;
               req.package             = [dict objectForKey:@"package"];
               req.sign                = [dict objectForKey:@"sign"];
               [WXApi sendReq:req];
           }
           else
           {
               JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"提示" message:@"支付订单生成失败，请重试"];
               [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
               }];
               [alert show];
           }
       } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
           [MBProgressHUD showError:@"充值服务器异常"];
       }];
       

    }
    else
    {
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"提示" message:@"请选择支付方式"];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
        }];
        [alert show];

    }
    
}
-(void)onReq:(BaseReq *)req
{
    
}
-(void)onResp:(BaseResp *)resp
{
    if ([resp isKindOfClass:[PayResp class]])
    {
        PayResp *response = (PayResp *)resp;
        switch (response.errCode) {
            case WXSuccess: {
                __weak typeof(self) weakSelf = self;
                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"结果" message:@"充值成功"];
                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }];
                [alert show];
                break;
            }
            case WXErrCodeUserCancel: {
                
                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"结果" message:@"用户取消支付"];
                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                }];
                [alert show];
                
                break;
            }
            default: {
                
                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"结果" message:@"支付失败"];
                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                }];
                [alert show];
                
                break;
            }
        }
    }
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *respones = (SendAuthResp*)resp;
        switch (respones.errCode) {
            case WXSuccess: {
                if ([self.delagate respondsToSelector:@selector(didGetAuthResp:)]) {
                    [self.delagate didGetAuthResp:respones];
                }
                break;
            }
            case WXErrCodeUserCancel: {
                
                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"结果" message:@"用户取消绑定"];
                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                }];
                [alert show];
                
                break;
            }
            default: {
                
                JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"结果" message:@"绑定失败"];
                [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
                }];
                [alert show];
                
                break;
            }
        }
    }
}
@end
